﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

using CE.Image;
using CE.User;
using CE.Mail;

public partial class Provider_ChangePassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("providersecurelogin.aspx");
            }
        }
        else
        {
            Response.Redirect("providersecurelogin.aspx");
        }

        if (Session["ImageCount"] != null)
        {
            if (Convert.ToInt32(Session["ImageCount"].ToString()) > 5)
            {
                lblMessage.Text = "Please try after a few moment! You are session has been locked!";
                btnSubmit.Enabled = false;
                btnNewImage.Enabled = false;
                txtOldPassword.Enabled = false;
                txtSecurityCode.Enabled = false;
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                Response.Redirect("usermessage.aspx?mt=UM&ec=1993");
            }
            else
            {
                lblMessage.Text = "";
                btnSubmit.Enabled = true;
                btnNewImage.Enabled = true;
                txtOldPassword.Enabled = true;
                txtSecurityCode.Enabled = true;
            }
        }

        if (!Page.IsPostBack)
        {
            if (Session["ImageCount"] != null)
            {
                if (Convert.ToInt32(Session["ImageCount"].ToString()) <= 5)
                {
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                CreateUpdateImageAndSession();
            }
        }
    }

    private void CreateUpdateImageAndSession()
    {
        MyImage myimage = new MyImage();
        //MemoryStream memoStrem = new MemoryStream();
        string salt = "";

        if (Session[CE.Global.General.SecurityCheckWord] != null)
        {
            salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        }
        else
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
            }
            else
            {
                salt = myimage.GetRandomWord("all");
            }
        }

        //txtSecurityCode.MaxLength = salt.Length;
        //salt = CE.Security.MySecurity.Encrypt(salt, true);
        Session[CE.Global.General.SecurityCheckWord] = salt;
        //ViewState[CE.Global.General.SecurityCheckWord] = salt;
        //if (salt.Contains("+"))
        //{
        //    salt = salt;
        //}
        imgCAPTCHA.ImageUrl = @"~/CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        txtSecurityCode.Text = "";
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        CreateUpdateImageAndSession();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                string _usrText = txtSecurityCode.Text.ToUpper();
                string _imgText = Session[CE.Global.General.SecurityCheckWord].ToString().ToUpper();
                //if (CE.Security.MySecurity.Encrypt(txtSecurityCode.Text, true) == ViewState[CE.Global.General.SecurityCheckWord].ToString())
                if (_usrText == _imgText)
                {
                    AccountDB _accountdb = new AccountDB();
                    Account _account = _accountdb.CheckEmail(Session[CE.Global.General.UserEmail].ToString(), Convert.ToInt32(CE.Global.CEUserType.Provider));
                    if (_account != null)
                    {
                        string _oldPassword = txtOldPassword.Text;
                        string _newPassword = txtNewPassword.Text;
                        //Response.Write(_account.AuthCode);
                        if (_account.AuthCode == _oldPassword)
                        {
                            _account.AuthCode = _newPassword;
                            if (_accountdb.Insert(_account) > 0)
                            {
                                AccountStatusDB _accountStatusDB = new AccountStatusDB();
                                if (_accountStatusDB.UpdatePasswordChangedDate(_account.CEID, CE.Global.General.GetUTCDateTime()))
                                {   //Response.Redirect("UserMessage.aspx?ErrorCode=1991");
                                    lblMessage.Text = "New password has been changed. Redireting to home page.";

                                    btnSubmit.Enabled = false;
                                    //System.Threading.Thread.Sleep(5000);
                                    Response.Redirect("providerhome.aspx");
                                }
                                else
                                {
                                    lblMessage.Text = "Error in new password change process.";
                                }
                            }
                            else
                            {
                                lblMessage.Text = "Change password failed!Try again later!";
                                CreateUpdateImageAndSession();
                            }
                        }
                        else
                        {
                            lblMessage.Text = "Old password is wrong.";
                            CreateUpdateImageAndSession();
                        }
                    }
                    else
                    {
                        lblMessage.Text = "No such email found.!";
                        CreateUpdateImageAndSession();
                    }
                }
                else
                {
                    lblMessage.Text = "Wrong Security check!";
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                lblMessage.Text = "Security Check code was expired. Please try again.";
                CreateUpdateImageAndSession();
            }
        }
    }

    protected void CheckPasswordLength(object source, ServerValidateEventArgs args)
    {
        try
        {
            // Test whether the lenght of value is < 7 or Is Number Value.
            string valArgs = args.Value;
            if (valArgs.IndexOf(' ') != -1 || valArgs.IndexOf('\'') != -1 ||
                valArgs.IndexOf('\"') != -1 || valArgs.IndexOf('~') != -1)
            {
                ((CustomValidator)source).ErrorMessage = "Password include invalid character or space!";
                ((CustomValidator)source).Text = "Password include invalid character or space!";
                args.IsValid = false;
            }
            else if (args.Value.Trim().Length < 8)
            {
                ((CustomValidator)source).ErrorMessage = "Password length should be at 8!";
                ((CustomValidator)source).Text = "Password length should be at 8!";
                args.IsValid = false;
            }
            else if (args.Value.Trim().Length > 20)
            {
                ((CustomValidator)source).ErrorMessage = "Password length should not be over 20!";
                ((CustomValidator)source).Text = "Password length should not be over 20!";
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
        catch (Exception ex)
        {
            args.IsValid = false;
        }
    }

    protected void CheckValidPassword(object source, ServerValidateEventArgs args)
    {
        try
        {       
            string valArgs = args.Value;
            string strRegex = @"^\w*(?=\w*\d{2})(?=\w*[a-z]{2})(?=\w*[A-Z]{2})\w{8,20}$"; 
            Regex ValStr = new Regex(strRegex);
            if (!ValStr.IsMatch(valArgs))
            {
                ((CustomValidator)source).ErrorMessage = "Password must be two upper, two lower, two digits and (8-20) characters long.";
                ((CustomValidator)source).Text = "Password must be two upper, two lower, two digits and (8-20) characters long.";
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
        catch(Exception ex)
        {
            args.IsValid = false;
        }
    }

    public string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] buff = new Byte[size];
        rng.GetBytes(buff);

        return Convert.ToBase64String(buff);
    }

    //public string EncrptString(string strOriginal)
    //{
    //    Byte[] clearByte;
    //    UnicodeEncoding unEncode = new UnicodeEncoding();
    //    clearByte = unEncode.GetBytes(strOriginal);
    //    HashAlgorithm hsAlgo = CryptoConfig.CreateFromName("MD5");
    //    Byte[] hsByte = hsAlgo.ComputeHash(clearByte);
    //    string strHash = BitConverter.ToString(hsByte);
    //    return strHash;
    //}

    //public string DecryptString(string strOriginal)
    //{

    //}
}
